package com.byit.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.builder.MapBuilder;
import com.byit.config.MinioConfig;
import com.byit.constant.DefaultValue;
import com.byit.domain.AppMail;
import com.byit.enums.PromptInfo;
import com.byit.log.ChannelType;
import com.byit.log.Log;
import com.byit.log.OperatorType;
import com.byit.mail.MailMessage;
import com.byit.mail.SendMailService;
import com.byit.msg.MessageResult;
import com.byit.service.IAppMailService;
import com.byit.service.IAppNewsService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @ClassName AppMailController
 * @Description 邮件服务管理
 * @Author lxp
 * @Date 2019-01-21 17:35
 **/
@RestController
@RequestMapping("/api/sys/appMail")
public class AppMailController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private IAppMailService mailService;

    @Autowired
    private SendMailService sendMailService;

    @Autowired
    private IAppNewsService appNewsService;

    @Autowired
    private MinioConfig minioConfig;

    /**
     * 新增或修改邮件服务信息
     *
     * @param session
     * @return
     */
    @PostMapping("/add")
    @Log(title = "邮件服务", operate = OperatorType.DATA_INSERT, channel = ChannelType.WEB_INTER)
    public Object insertAnnouncement(HttpSession session, AppMail appMail,
                                     @RequestParam(value = "url", defaultValue = "") String url
    ) {

        // String path = appNe
        // wsService.getPictrePath(file, "mailAttachment");
        if (StringUtils.isNotEmpty(url)) {
            appMail.setUrl(url);
        }
        Long companyId = SessionHelper.getCompanyId(session);
        Long userId = SessionHelper.getUserId(session);
        try {
            if (null == appMail) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            if (appMail.getContent() == null || appMail.getContent().length() < 100) {
                return MessageResult.warpper("001", null, "内容不少于100字符");
            }
            appMail.setCreateTime(new Date());
            appMail.setUpdateTime(new Date());
            //// 加密用户密码
            appMail.setOperationId(userId);

            mailService.insertOrUpdate(appMail);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 新增或修改邮件服务信息
     *
     * @param session
     * @return
     */
    @PostMapping("/edit")
    @Log(title = "邮件服务", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    public Object edit(HttpSession session, AppMail appMail
            , @RequestParam(value = "url", defaultValue = "") String url) {

        Long userId = SessionHelper.getUserId(session);
        // String path = appNewsService.getPictrePath(file, "appMailAtachement");
         //   appMail.setUrl(url);
        //校验
        if (mailService.selectById(appMail.getId()).getIsSend()==1) {
            return MessageResult.error("已发送,不可编辑");
        }

        try {
            if (StringUtil.isEmpty(appMail.getId())) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            if (appMail.getContent() == null || appMail.getContent().length() < 100) {
                return MessageResult.warpper("001", null, "内容不少于100字符");
            }
            appMail.setCreateTime(new Date());
            appMail.setUpdateTime(new Date());
            //// 加密用户密码
            appMail.setOperationId(userId);

            mailService.insertOrUpdate(appMail);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 通过Id查询邮件服务
     *
     * @param id
     * @return
     */
    @GetMapping("/details")
    @Log(title = "邮件服务", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object selectAppNewsById(@RequestParam("id") Integer id) {
        AppMail appMail = mailService.selectById(id);
       /* String searchMinio = appNewsService.getSearchMinio();
        appNews.setPicture(searchMinio + appNews.getPicture());*/
        return MessageResult.success(appMail);
    }

    /**
     * 按照条件查询邮件服务
     *
     * @param session
     * @param title
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    @Log(title = "邮件服务", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object appMailList(HttpSession session,
                              @RequestParam(value = "title", defaultValue = "") String title,
                              @RequestParam(value = "sendTo", defaultValue = "") String sendTo,
                              @RequestParam(value = "fromTo", defaultValue = "") String fromTo,
                              @RequestParam(value = "fromTo", defaultValue = "") String isSend,
                              @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                              @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {
        Page<AppMail> pageInfo = new Page<>(page, limit);
        //新闻权限控制
        Long companyId = SessionHelper.getCompanyId(session);

        Map<String, Object> params = MapBuilder.newMap(5).setParam("isSend", isSend)
                .ok();
        if (null != title && !"".equals(title)) {
            params.put("title", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(title) + "%");
        }
        if (null != sendTo && !"".equals(sendTo)) {
            params.put("sendTo", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(sendTo) + "%");
        }
        if (null != fromTo && !"".equals(fromTo)) {
            params.put("fromTo", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(fromTo) + "%");
        }
        Page<JSONObject> result = mailService.selectAppMailPageList(pageInfo, params);

        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, result);
    }

    /**
     * 逻辑删除邮件服务信息
     *
     * @param session
     * @param ids
     * @return
     */
    @PostMapping("/del")
    @Log(title = "邮件服务", operate = OperatorType.DATA_DELETE, channel = ChannelType.WEB_INTER)
    public Object delAppNewsByIds(HttpSession session, @RequestParam("ids") String ids) {
        Long userId = SessionHelper.getUserId(session);
        List<Long> idList = StringUtil.splitLong(ids, ",");
        Map<String, Object> map = MapBuilder.newMap(3).setParam("updateTime", new Date()).setParam("operId", userId).ok();


        for (Long id : idList) {
            //校验
            if (mailService.selectById(id).getIsSend()==1) {
                return MessageResult.error("已发送邮件,请勿删除");
            }

            map.put("id", id);
            mailService.deleteAppMailById(map);
        }
        return MessageResult.success();
    }

    /**
     * 发送
     *
     * @param session
     * @return
     */
    @PostMapping("/send")
    @Log(title = "邮件服务", operate = OperatorType.DATA_INSERT, channel = ChannelType.WEB_INTER)
    public Object send(HttpSession session, @RequestParam("id") Integer id) {

        Long userId = SessionHelper.getUserId(session);

        //校验
        if (mailService.selectById(id).getIsSend()==1) {
            return MessageResult.error("请勿重复发送");
        }
        AppMail appMail = mailService.selectById(id);
        String attachementUtl= null;
        if (StringUtils.isNotEmpty(appMail.getUrl())) {
            attachementUtl = minioConfig.getSearchMinio() + appMail.getUrl();
        }
        try {
            if (null == appMail) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            if (appMail.getContent() == null || appMail.getContent().length() < 100) {
                return MessageResult.warpper("001", null, "内容不少于100字符");
            }
            MailMessage mailMessage = new MailMessage();
            mailMessage.setTemplateId("email-template");
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("username", appMail.getSendTo());
            paramMap.put("content", appMail.getContent());
            paramMap.put("attachementUtl", attachementUtl);
            mailMessage.setParamMap(paramMap);
            //  mailMessage.setFrom(appMail.getFromTo());
            mailMessage.setToList(Arrays.asList(appMail.getSendTo().split(",")));
            mailMessage.setSubject(appMail.getTitle());

            /*if (!sendMailService.sendTemplate(mailMessage)) {
                return MessageResult.warpper("001", null, "发送失败");
            }*/
            if (!sendMailService.send(mailMessage)) {
                return MessageResult.warpper("001", null, "发送失败");
            }
            appMail.setCreateTime(new Date());
            appMail.setUpdateTime(new Date());
            //// 加密用户密码
            appMail.setOperationId(userId);
            appMail.setIsSend(1);
            mailService.insertOrUpdate(appMail);
            //发送邮件
            // sendMailService.sendSample(null);
            // Map<String, Object> map = new HashMap<>();
            // map.put("file", file);
            // sendMailService.sendAttachmentsMail(map);


            return MessageResult.warpper("000", null, "发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }
}
